import React, { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, NavBar, Toast } from "antd-mobile";
import http from "../../utils/http";
import useCountDown from "../../hook/useCountDown";

const Index = () => {
  const navigate = useNavigate();
  const { countDown, isRuning, startCountDown } = useCountDown(10);
  const [from] = Form.useForm();

  const codeText = useMemo(() => {
    if (isRuning) {
      return `${countDown} 秒后重新获取`;
    } else {
      return "获取验证码";
    }
  }, [countDown]);

  const handelEmitCode = () => {
    from.validateFields(["tel"]).then(async ({ tel }) => {
      //开始倒计时
      startCountDown();

      //请求接口获取验证码
      const res = await http.get("/api/login/code", { params: { tel } });
      const { code, message, data } = res.data;
      if (code === 200) {
        from.setFieldValue("telCode", data);
      } else {
        Toast.show({
          icon: "fail",
          content: message,
        });
      }
    });
  };

  //提交表单
  const onFinish = async (values) => {
    const res = await http.post("/api/login/tel", values);
    const { code, message, data } = res.data;
    if (code === 200) {
      localStorage.setItem("userInfo", JSON.stringify(data.userInfo));
      localStorage.setItem("token", data.token);
      navigate("/");
    } else {
      Toast.show({
        icon: "fail",
        content: message,
      });
    }
  };

  return (
    <div>
      <NavBar backIcon={false}>手机号登陆</NavBar>

      <Form
        form={from}
        onFinish={onFinish}
        layout="horizontal"
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Header>火车票订票系统登陆</Form.Header>
        <Form.Item
          name="tel"
          label="用户名"
          rules={[
            {
              required: true,
              message: "用户名格式输入不正确",
              pattern: /^1[3-9]\d{9}$/, //手机号正则
            },
          ]}
        >
          <Input placeholder="请输入用户名：邮箱" />
        </Form.Item>
        <Form.Item
          name="telCode"
          label="短信验证码"
          extra={
            <Button
              disabled={isRuning ? true : false}
              onClick={() => handelEmitCode()}
            >
              {codeText}
            </Button>
          }
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
};
export default Index;
